<script setup>
import { ref, computed } from 'vue'
import { Checkbox, Button, InputNumber, Message } from '@arco-design/web-vue'

// 可用的字段列表
const availableFields = ref([
    { id: 'field_title', type: 'text', label: '准考证', key: 'title', selected: true, scale: 1, rotation: 0, value: '准考证' },
    { id: 'field_name_label', type: 'text', label: '姓名：', key: 'nameLabel', selected: true, scale: 1, rotation: 0, value: '姓名：' },
    { id: 'field_name', type: 'text', label: '姓名值', key: 'name', selected: true, scale: 1, rotation: 0, value: '赵哈哈' },
    { id: 'field_sex_label', type: 'text', label: '性别：', key: 'sexLabel', selected: true, scale: 1, rotation: 0, value: '性别：' },
    { id: 'field_sex', type: 'text', label: '性别值', key: 'sex', selected: true, scale: 1, rotation: 0, value: '女' },
    { id: 'field_school_label', type: 'text', label: '学校名称：', key: 'schoolLabel', selected: true, scale: 1, rotation: 0, value: '学校名称：' },
    { id: 'field_school', type: 'text', label: '学校名称值', key: 'schoolName', selected: true, scale: 1, rotation: 0, value: '光谷第子路小学' },
    { id: 'field_grade_label', type: 'text', label: '年级班级：', key: 'gradeLabel', selected: true, scale: 1, rotation: 0, value: '年级班级：' },
    { id: 'field_grade', type: 'text', label: '年级班级值', key: 'grade', selected: true, scale: 1, rotation: 0, value: '一年级1班' },
    { id: 'field_study_label', type: 'text', label: '学籍号：', key: 'studyLabel', selected: true, scale: 1, rotation: 0, value: '学籍号：' },
    { id: 'field_study', type: 'text', label: '学籍号值', key: 'studyCode', selected: true, scale: 1, rotation: 0, value: 'G411152420160926168' },
    { id: 'field_qrcode', type: 'qrcode', label: '二维码', key: 'qrcode', selected: true, scale: 1, rotation: 0 },
    { id: 'field_subjects', type: 'subjects', label: '考试科目', key: 'subjects', selected: true, scale: 1, rotation: 0, value: ['身高体重', '肺活量', '50米跑', '坐位体前屈', '一分钟仰卧起坐', '一分钟跳绳'] },
    { id: 'field_notice', type: 'text', label: '注意事项', key: 'notice', selected: true, scale: 1, rotation: 0, value: '避免准考证二维码磨损或者弯折破损' }
])

// 已放置的字段
const placedFields = ref([])

// 历史记录
const history = ref([])
const historyIndex = ref(-1)

// 网格设置
const showGrid = ref(false)
const gridSize = ref(10)

// 计算已选中的字段
const updatePlacedFields = () => {
    const newFields = availableFields.value
        .filter(field => field.selected)
        .map(field => {
            let width = 80
            let height = 24
            let x = 10
            let y = 10

            // 根据字段类型设置不同的默认位置和大小
            switch (field.id) {
                case 'field_title':
                    x = 120
                    y = 10
                    width = 60
                    height = 24
                    break
                case 'field_name_label':
                    x = 20
                    y = 40
                    width = 40
                    height = 24
                    break
                case 'field_name':
                    x = 60
                    y = 40
                    width = 80
                    height = 24
                    break
                case 'field_sex_label':
                    x = 150
                    y = 40
                    width = 40
                    height = 24
                    break
                case 'field_sex':
                    x = 190
                    y = 40
                    width = 30
                    height = 24
                    break
                case 'field_school_label':
                    x = 20
                    y = 70
                    width = 80
                    height = 24
                    break
                case 'field_school':
                    x = 100
                    y = 70
                    width = 160
                    height = 24
                    break
                case 'field_grade_label':
                    x = 20
                    y = 100
                    width = 80
                    height = 24
                    break
                case 'field_grade':
                    x = 100
                    y = 100
                    width = 160
                    height = 24
                    break
                case 'field_study_label':
                    x = 20
                    y = 130
                    width = 80
                    height = 24
                    break
                case 'field_study':
                    x = 100
                    y = 130
                    width = 160
                    height = 24
                    break
                case 'field_qrcode':
                    x = 270
                    y = 20
                    width = 80
                    height = 80
                    break
                case 'field_subjects':
                    x = 20
                    y = 160
                    width = 330
                    height = 140
                    break
                case 'field_notice':
                    x = 20
                    y = 250
                    width = 330
                    height = 24
                    break
            }

            return {
                ...field,
                id: `placed_${field.id}`,
                x,
                y,
                width,
                height
            }
        })

    placedFields.value = newFields
    saveHistory()
}

// 保存历史记录
const saveHistory = () => {
    // 删除当前位置之后的历史记录
    history.value = history.value.slice(0, historyIndex.value + 1)
    // 添加新的状态
    history.value.push(JSON.stringify(placedFields.value))
    historyIndex.value = history.value.length - 1
}

// 撤销
const undo = () => {
    if (historyIndex.value > 0) {
        historyIndex.value--
        placedFields.value = JSON.parse(history.value[historyIndex.value])
    }
}

// 重做
const redo = () => {
    if (historyIndex.value < history.value.length - 1) {
        historyIndex.value++
        placedFields.value = JSON.parse(history.value[historyIndex.value])
    }
}

// 监听字段选择变化
const handleCheckboxChange = (field) => {
    field.selected = !field.selected
    updatePlacedFields()
}

// 选择字段
const selectField = (field) => {
    selectedField.value = field
}

// 对齐到网格
const snapToGrid = (value) => {
    return Math.round(value / gridSize.value) * gridSize.value
}

// 处理拖拽结束
const handleDragEnd = (evt) => {
    const { item } = evt
    const fieldId = item.getAttribute('data-id')
    const field = placedFields.value.find(f => f.id === fieldId)
    if (field) {
        const rect = item.getBoundingClientRect()
        const container = document.querySelector('.ticket-content')
        const containerRect = container.getBoundingClientRect()

        // 应用网格对齐
        field.x = showGrid.value
            ? snapToGrid(rect.left - containerRect.left)
            : rect.left - containerRect.left
        field.y = showGrid.value
            ? snapToGrid(rect.top - containerRect.top)
            : rect.top - containerRect.top

        saveHistory()
    }
}

// 添加位置更新处理函数
const onDragStop = (x, y, field) => {
    field.x = x
    field.y = y
    saveHistory()
}

// 添加大小更新处理函数
const onResizeStop = (x, y, width, height, field) => {
    field.x = x
    field.y = y
    field.width = width
    field.height = height
    saveHistory()
}

// 添加一个计算属性来处理科目分组
const getSubjectRows = (subjects) => {
    const rows = []
    for (let i = 0; i < subjects.length; i += 4) {
        rows.push(subjects.slice(i, i + 4))
    }
    return rows
}

// 修改导出模板函数
const exportTemplate = () => {
    // 生成 Freemarker 模板内容
    let template = `<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        .admission-ticket {
            width: 100mm;
            height: 95mm;
            position: relative;
            border: 1px solid #000;
            box-sizing: border-box;
            font-family: SimSun;
        }
        .field-item {
            position: absolute;
            font-size: 14px;
            line-height: 1.5;
        }
        .subjects-table {
            border-collapse: collapse;
            width: 100%;
        }
        .subjects-table td {
            border: 1px solid #000;
            text-align: center;
            padding: 4px;
            height: 28px;
        }
    </style>
</head>
<body>
    <div class="admission-ticket">`

    // 添加字段
    placedFields.value.forEach(field => {
        const style = `position: absolute; left: ${field.x}px; top: ${field.y}px; width: ${field.width}px; height: ${field.height}px;`

        switch (field.type) {
            case 'text':
                // 根据字段的 key 使用对应的 Freemarker 变量
                let value = field.value // 默认使用静态值
                if (field.key === 'name') {
                    value = '<#if student??>${student.name!""}</#if>'
                } else if (field.key === 'sex') {
                    value = '<#if student??>${student.sex!""}</#if>'
                } else if (field.key === 'schoolName') {
                    value = '<#if student??>${student.schoolName!""}</#if>'
                } else if (field.key === 'grade') {
                    value = '<#if student??>${student.gradeName!""}</#if>'
                } else if (field.key === 'studyCode') {
                    value = '<#if student??>${student.studyCode!""}</#if>'
                } else if (field.key === 'notice') {
                    value = '<#if notice??>${notice!""}</#if>'
                }
                template += `\n        <div class="field-item" style="${style}">${value}</div>`
                break

            case 'qrcode':
                template += `\n        <div class="field-item" style="${style}">
            <#if student?? && student.qrCodeUrl??><img src="\${student.qrCodeUrl}" style="width: 100%; height: 100%;" /></#if>
        </div>`
                break

            case 'subjects':
                template += `\n        <div class="field-item" style="${style}">
            <table class="subjects-table">
                <#if subjects?? && subjects?size gt 0>
                    <#assign rows = (subjects?size + 3) / 4>
                    <#list 0..(rows-1) as row>
                        <tr>
                            <#list row * 4..(row * 4 + 3) as col>
                                <td><#if subjects[col]??>\${subjects[col].name!""}</#if></td>
                            </#list>
                        </tr>
                        <tr>
                            <#list row * 4..(row * 4 + 3) as col>
                                <td><#if subjects[col]??>\${subjects[col].score!""}</#if></td>
                            </#list>
                        </tr>
                    </#list>
                </#if>
            </table>
        </div>`
                break
        }
    })

    template += `\n    </div>
</body>
</html>`

    // 创建并下载文件
    const blob = new Blob([template], { type: 'text/plain;charset=utf-8' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = 'admission_ticket_template.ftl'
    link.click()
    URL.revokeObjectURL(link.href)
    Message.success('模板已导出')
}

// 初始化已选中的字段
updatePlacedFields()
saveHistory()
</script>

<template>
    <div class="admission-ticket-designer">
        <!-- 工具栏 -->
        <div class="toolbar">
            <Button type="outline" size="small" @click="undo" :disabled="historyIndex <= 0">
                <template #icon>
                    <IconUndo />
                </template>
                撤销
            </Button>
            <Button type="outline" size="small" @click="redo" :disabled="historyIndex >= history.length - 1">
                <template #icon>
                    <IconRedo />
                </template>
                重做
            </Button>
            <Button type="outline" size="small" @click="showGrid = !showGrid" :type="showGrid ? 'primary' : 'outline'">
                网格
            </Button>
            <InputNumber v-if="showGrid" v-model="gridSize" :min="5" :max="50" size="small" style="width: 80px" />
            <Button type="primary" size="small" @click="exportTemplate">
                导出模板
            </Button>
        </div>

        <div class="design-layout">
            <!-- 左侧字段列表 -->
            <div class="fields-panel">
                <h3>可用字段</h3>
                <div class="fields-list">
                    <div v-for="field in availableFields" :key="field.id" class="field-item-source">
                        <Checkbox :model-value="field.selected" @change="() => handleCheckboxChange(field)">
                            {{ field.label }}
                        </Checkbox>
                    </div>
                </div>
            </div>

            <!-- 右侧设计区域 -->
            <div class="design-area">
                <div class="design-container">
                    <div class="size-reference">100mm × 95mm (1/6 A4)</div>
                    <div class="ticket-container">
                        <vue-draggable-resizable v-for="field in placedFields" :key="field.id" :x="field.x" :y="field.y"
                            :w="field.width" :h="field.height" :parent="true" :draggable="true" :resizable="true"
                            :min-width="60" :min-height="24" :grid="showGrid ? [gridSize, gridSize] : [1, 1]"
                            @dragstop="(x, y) => onDragStop(x, y, field)"
                            @resizestop="(x, y, width, height) => onResizeStop(x, y, width, height, field)">
                            <template v-if="field.type === 'qrcode'">
                                <div class="qrcode-placeholder">
                                    <img v-if="field.value" :src="field.value" alt="二维码" />
                                    <span v-else>二维码</span>
                                </div>
                            </template>
                            <template v-else-if="field.type === 'subjects'">
                                <div class="subjects-table">
                                    <table>
                                        <template v-for="(row, rowIndex) in getSubjectRows(field.value)"
                                            :key="rowIndex">
                                            <!-- 项目名称行 -->
                                            <tr>
                                                <td v-for="(subject, colIndex) in row" :key="colIndex">{{ subject }}
                                                </td>
                                                <!-- 如果这一行不足4个，补充空单元格 -->
                                                <td v-for="i in 4 - row.length" :key="'empty-' + i"></td>
                                            </tr>
                                            <!-- 成绩行 -->
                                            <tr>
                                                <td v-for="(_, colIndex) in row" :key="colIndex"></td>
                                                <!-- 如果这一行不足4个，补充空单元格 -->
                                                <td v-for="i in 4 - row.length" :key="'empty-score-' + i"></td>
                                            </tr>
                                        </template>
                                    </table>
                                </div>
                            </template>
                            <template v-else>
                                <div class="text-content">
                                    {{ field.value || field.label }}
                                </div>
                            </template>
                        </vue-draggable-resizable>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped lang="less">
.admission-ticket-designer {
    padding: 20px;

    .toolbar {
        margin-bottom: 16px;
        display: flex;
        gap: 8px;
        align-items: center;
    }

    .design-layout {
        display: flex;
        gap: 20px;
        min-height: calc(100vh - 40px);
    }

    .fields-panel {
        width: 200px;
        background: var(--color-bg-2);
        padding: 16px;
        border-radius: 4px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        height: fit-content;

        h3 {
            margin: 0 0 16px 0;
            font-size: 16px;
            color: var(--color-text-1);
        }

        .fields-list {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }

        .field-item-source {
            padding: 4px 8px;
            border-radius: 4px;
            user-select: none;

            &:hover {
                background: var(--color-fill-2);
            }
        }
    }

    .design-area {
        flex: 1;
        background: var(--color-fill-2);
        padding: 20px;
        display: flex;
        justify-content: center;
    }

    .design-container {
        width: 100mm;
        background: var(--color-bg-2);
        margin: 0 auto;
        padding: 5mm;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }

    .ticket-container {
        border: 1px solid var(--color-border);
        position: relative;
        height: 95mm;
        width: 100%;
        background: white;

        .ticket-content {
            position: relative;
            width: 100%;
            height: 100%;
            min-height: 95mm;
        }
    }

    .field-item {
        background: transparent;
        border: none;
        display: flex;
        align-items: center;
        overflow: hidden;

        .text-content {
            width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            padding: 0 4px;
            font-size: 14px;
        }
    }

    .avatar-placeholder,
    .qrcode-placeholder {
        width: 100%;
        height: 100%;
        background: var(--color-fill-2);
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;

        img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }
    }

    .subjects-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 5px;
        width: 200px;

        .subject-cell {
            height: 30px;
            border: 1px solid var(--color-border);
        }
    }

    .grid-background {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-image:
            linear-gradient(to right, var(--color-border) 1px, transparent 1px),
            linear-gradient(to bottom, var(--color-border) 1px, transparent 1px);
        opacity: 0.2;
        pointer-events: none;
    }

    .field-item {
        &.selected {
            border: 2px solid rgb(var(--primary-6));
            z-index: 2;
        }
    }

    .properties-panel {
        display: none;
    }

    .size-reference {
        position: absolute;
        top: -20px;
        left: 0;
        width: 100%;
        text-align: center;
        color: var(--color-text-3);
        font-size: 12px;
    }
}

.ghost {
    opacity: 0.5;
    background: var(--color-fill-2) !important;
    border: 2px dashed rgb(var(--primary-6)) !important;
}

.chosen {
    border: 2px solid rgb(var(--primary-6)) !important;
    background: var(--color-bg-2) !important;
}

.drag {
    opacity: 0.8;
    cursor: grabbing !important;
    z-index: 999 !important;
}

.field-item-active {
    border: 2px solid rgb(var(--primary-6)) !important;
    z-index: 2;
}

.subjects-table {
    width: 100%;
    height: 100%;
    overflow: hidden;

    table {
        width: 100%;
        border-collapse: collapse;

        td {
            border: 1px solid #000;
            text-align: center;
            padding: 4px;
            font-size: 14px;
            height: 28px;
            width: 25%;
            vertical-align: middle;
        }
    }
}
</style>